/**
 * Created by zhangguoqing on 2016/6/24.
 */


/**
 * role-insert 入口
 * */
$(document).ready(function(){
	//模块总数量
	var moduleSize = $("#moduleSize").val();
	roleAllSelectCheckBox();
	roleAllGiveUpCheckBox();
	funModuleAllSelectCheckBox(moduleSize);
	roleNameValidate();
	
	$("#commitBtn").click(function(){
		var url = getRootPath() + "/role/insert";
		var functionIds = requestData();
		var roleName = $("#role-name").val();
		var desc = $("#desc").val();
		$.post(url,{"functionIds":functionIds.join(","),"roleName":roleName,"desc":desc},function(data){
			if(data.success == true){
				swal("创建成功", data['message'], 'success');
			}else if(data.success == false){
				swal("失败", data['message'], 'error');
			}else{
				swal("失败", data['message'], 'error');
			}
		});
		
	});
	
	$("#updateBtn").click(function(){
		var url = getRootPath() + "/role/update";
		var functionIds = requestData();
		var roleName = $("#role-name").val();
		var desc = $("#desc").val();
		var roleId = $("#roleUpdateId").val();
		$.post(url,{"roleId":roleId,"functionIds":functionIds.join(","),"roleName":roleName,"desc":desc},function(data){
			if(data.success == true){
				swal("创建成功", data['message'], 'success');
			}else if(data.success == false){
				swal("失败", data['message'], 'error');
			}else{
				swal("失败", data['message'], 'error');
			}
		});
	});
	
});


/**
 * 获取项目根路径
 * */
function getRootPath(){
	return contextPath;
}


/**
 * 角色名称ajax 判断唯一性
 * */
function roleNameValidate(){
	var url = getRootPath() + "/role/findRoleName";
	$("#role-name").on("blur",function(){
		var roleName = $("#role-name").val();
		$.post(url,{'roleName':roleName},function(data){
			if(data.success == false){
				swal("失败", data['message'], 'error');
			}
		})
	})
}


/**
 * 全选 checkBox
 * */
function roleAllSelectCheckBox(){
	$("#roleAllSelectCheckBox").click(function(){
		$.each($(".functionCheckBox"),function(){
			this.checked = true;
		})
	});
}


/**
 * 全不选
 * */
function roleAllGiveUpCheckBox(){
	$("#roleAllGiveUpCheckBox").click(function(){
		$.each($(".functionCheckBox"),function(){
			this.checked = false;
		})
	});
}

/**
 * 各个功能模块的 全选//各个功能模块的 全不选
 * */
function funModuleAllSelectCheckBox(moduleSize){
	for(var i=1;i<=moduleSize;i++){
		$("#selectCheckBox_"+i).click(function(){
			$.each($(this).parent().find(".functionCheckBox"),function(){
				this.checked = true;
			});
		});
		$("#giveUpCheckBox_"+i).click(function(){
			$.each($(this).parent().find(".functionCheckBox"),function(){
				this.checked = false;
			});
		});
	}
}


/**
 * 获取被选中的复选框的value值 
 * @param checkArray
 * */
function requestData(){
	var checkArray = new Array();
	$('input[class="functionCheckBox"]:checked').each(function(){
		checkArray.push($(this).val());
	})
	return checkArray;
}